package com.jprocms.module.cms.controller.admin.globalconfig;

import com.jpro.framework.common.pojo.CommonResult;
import com.jprocms.module.cms.api.dto.EmailConfig;
import com.jprocms.module.cms.api.dto.GlobalConfigRespVO;
import com.jprocms.module.cms.controller.admin.globalconfig.vo.GlobalConfigUpdateReqVO;
import com.jprocms.module.cms.convert.globalconfig.GlobalConfigConvert;
import com.jprocms.module.cms.dal.dataobject.globalconfig.GlobalConfigDO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.framework.cache.CacheService;
import com.jprocms.module.cms.service.globalconfig.GlobalConfigService;
import com.jprocms.module.cms.service.site.SiteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

import static com.jpro.framework.common.pojo.CommonResult.success;
import static com.jprocms.module.cms.constant.CmsSysConstants.DESENS_STR;
import static com.jprocms.module.cms.dal.redis.RedisKeyConstants.CONFIG_UPDATE_TIME;

@Tag(name = "管理后台 - 系统配置")
@RestController
@RequestMapping("/cms/global-config")
@Validated
public class GlobalConfigController {

    @Resource
    private GlobalConfigService globalConfigService;
    @Resource
    private CacheService cacheService;
    @Resource
    private SiteService siteService;

    @PostMapping("/update")
    @Operation(summary = "更新系统配置")
    @PreAuthorize("@ss.hasPermission('cms:global-config:update')")
    public CommonResult<Boolean> updateGlobalConfig(@Valid @RequestBody GlobalConfigUpdateReqVO updateReqVO) {
        globalConfigService.updateGlobalConfig(updateReqVO);
        //通过更新redis时间，各个实例定时检查内存对象和redis的时间，如果redis有更新则取拉取否则跳过，没有才有消息队列是为了节省消息队列的部署
        cacheService.setCacheObject(CONFIG_UPDATE_TIME, System.currentTimeMillis());
        //site的二级缓存使用了GlobalConfig对象，这里主动更新site会触发缓存更新
        final List<SiteDO> siteList = siteService.getSiteList(updateReqVO.getId());
        siteService.updateBatchById(siteList);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得系统配置")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<GlobalConfigRespVO> getGlobalConfig() {
        GlobalConfigDO globalConfig = globalConfigService.getDefGlobalConfig();
        final GlobalConfigRespVO globalConfigRespVO = GlobalConfigConvert.INSTANCE.convert(globalConfig);
        final EmailConfig emailConfig = globalConfigRespVO.getEmailConfig();
        //脱敏密码
        emailConfig.setPassword(DESENS_STR);
        globalConfigRespVO.setEmailConfig(emailConfig);
        return success(globalConfigRespVO);
    }

}
